import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';

import 'package:flutter_screenutil/flutter_screenutil.dart';

class ChartApp extends StatelessWidget {
  const ChartApp({super.key});

  @override
  Widget build(BuildContext context) {
    return ScreenUtilInit(
      designSize: Size(750, 1334),
      child: WidgetsApp(
        debugShowCheckedModeBanner: false,
        color: Color(0xFFFFFFFF),
        builder: (_, appWidget) {
          return Container(
            width: 180,
            color: Color(0xFFFFFFFF),
            padding: EdgeInsets.only(top: 56.w),
            child: LineChart(),
          );
        },
      ),
    );
  }
}

class ChartHomePage extends StatefulWidget {
  const ChartHomePage({super.key, required this.title});

  final String title;

  @override
  State<ChartHomePage> createState() => _ChartHomePageState();
}

class _ChartHomePageState extends State<ChartHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[]),
      ),
    );
  }
}

// 曲线控制器
//
class ChartController extends GetxController {}

class LineChart extends StatefulWidget {
  const LineChart({super.key});

  @override
  State createState() => LineChartState();
}

class LineChartState extends State<LineChart> {
  late LineChartController lineChartController;

  String minX = "";
  late TextEditingController minXController;

  String maxX = "";
  late TextEditingController maxXController;

  @override
  void initState() {
    lineChartController = LineChartController();

    minXController = TextEditingController(text: minX);
    maxXController = TextEditingController(text: maxX);

    super.initState();
    // 设置 状态栏
    SystemChrome.setSystemUIOverlayStyle(
      SystemUiOverlayStyle(
        statusBarIconBrightness: Brightness.light,
        statusBarColor: Color(0x60000000),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      top: true,
      bottom: true,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          /// 折线图
          AxisWidget(lineChartController),
          Expanded(
            child: SingleChildScrollView(
              child: Column(
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        "横坐标 min  ",
                        style: TextStyle(color: Colors.black),
                      ),
                      Expanded(
                        child: Container(
                          height: 52.w,
                          decoration: BoxDecoration(border: Border.all(color: Colors.black12, width: 2.w)),
                          alignment: Alignment.center,
                          child: EditableText(
                            controller: minXController,
                            onChanged: (txt) {
                              print("$txt");
                            },
                            inputFormatters: [FilteringTextInputFormatter.allow(RegExp(r'[0-9]'))],
                            focusNode: FocusNode(),
                            style: TextStyle(color: Colors.black),
                            maxLines: 1,
                            cursorColor: Colors.blue,
                            backgroundCursorColor: Colors.amber,
                          ),
                        ),
                      ),
                    ],
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        "横坐标 max  ",
                        style: TextStyle(color: Colors.black),
                      ),
                      Expanded(
                        child: Container(
                          height: 52.w,
                          decoration: BoxDecoration(border: Border.all(color: Colors.black12, width: 2.w)),
                          alignment: Alignment.center,
                          child: EditableText(
                            controller: minXController,
                            onChanged: (txt) {
                              print("$txt");
                            },
                            inputFormatters: [FilteringTextInputFormatter.allow(RegExp(r'[0-9]'))],
                            focusNode: FocusNode(),
                            style: TextStyle(color: Colors.black),
                            maxLines: 1,
                            cursorColor: Colors.blue,
                            backgroundCursorColor: Colors.amber,
                          ),
                        ),
                      ),
                    ],
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        "纵坐标 min  ",
                        style: TextStyle(color: Colors.black),
                      ),
                      Expanded(
                        child: Container(
                          height: 52.w,
                          decoration: BoxDecoration(border: Border.all(color: Colors.black12, width: 2.w)),
                          alignment: Alignment.center,
                          child: EditableText(
                            controller: minXController,
                            onChanged: (txt) {
                              print("$txt");
                            },
                            inputFormatters: [FilteringTextInputFormatter.allow(RegExp(r'[0-9]'))],
                            focusNode: FocusNode(),
                            style: TextStyle(color: Colors.black),
                            maxLines: 1,
                            cursorColor: Colors.blue,
                            backgroundCursorColor: Colors.amber,
                          ),
                        ),
                      ),
                    ],
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        "纵坐标 max  ",
                        style: TextStyle(color: Colors.black),
                      ),
                      Expanded(
                        child: Container(
                          height: 52.w,
                          decoration: BoxDecoration(border: Border.all(color: Colors.black12, width: 2.w)),
                          alignment: Alignment.center,
                          child: EditableText(
                            controller: minXController,
                            onChanged: (txt) {
                              print("$txt");
                            },
                            inputFormatters: [FilteringTextInputFormatter.allow(RegExp(r'[0-9]'))],
                            focusNode: FocusNode(),
                            style: TextStyle(color: Colors.black),
                            maxLines: 1,
                            cursorColor: Colors.blue,
                            backgroundCursorColor: Colors.amber,
                          ),
                        ),
                      ),
                    ],
                  ),
                  GestureDetector(
                    onTap: () {
                      lineChartController.initLine1();
                    },
                    child: Container(
                      height: 52.w,
                      width: 375.w,
                      alignment: Alignment.center,
                      child: Text(
                        "刷新",
                        style: TextStyle(color: Colors.black, fontSize: 32.w),
                      ),
                    ),
                  )
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}

class LineInfoData {}

/// 控制器
class LineChartController extends GetxController {
  ValueNotifier repaint = ValueNotifier(0);

  // 绘制区域
  double w = 0;
  double h = 0;

  // 坐标轴信息
  // x轴起始点信息
  int startX = 0;

  // X 轴
  double minX = 0;
  double maxX = 10000;
  String xUnit = "m";

  // Y 轴
  double minY1 = 0;
  double maxY1 = 120;
  String y1Unit = "dB";

  // Y 轴2
  double minY2 = 0;
  double maxY2 = 120;

  // 画笔
  Paint paint = Paint()..color = Color(0xFF000000);

  // 文字
  Paint paintText = Paint()..color = Color(0xFF999999);

  List<double> line1 = [];
  List<double> line2 = [];
  List<double> line3 = [];
  List<double> line4 = [];

  // 曲线
  Paint paintLine1 = Paint()..color = Color(0xFF003333);
  Paint paintLine2 = Paint()..color = Color(0xFF330033);
  Paint paintLine3 = Paint()..color = Color(0xFF333300);
  Paint paintLine4 = Paint()..color = Color(0xFF303030);

  Paint paintPoint = Paint()
    ..color = Color(0xFFFF0000)
    ..strokeWidth = 4.w;

  Paint paintCurrent = Paint()
    ..color = Color(0xFF000000)
    ..strokeWidth = 4.w;

  int alphaValue = 255;
  int redValue = 0;
  int greenValue = 0;
  int blueValue = 0;

  changeColor(int r, int g, int b) {
    alphaValue = 255;
    redValue = r;
    greenValue = g;
    blueValue = b;
    paint.color = Color.fromARGB(alphaValue, redValue, greenValue, blueValue);
    repaint.value++;
    update();
  }

  changeY1(double min, double max) {
    print("修改: $min $max");
    minY1 = min;
    maxY1 = max;
    repaint.value++;
    update();
  }

  double width = 0.w;
  double height = 0.w;

  // 预留其他信息 , 减去后 剩余空间为绘制取件
  double left = 80.w;
  double top = 60.w;
  double right = 80.w;
  double bottom = 60.w;

  double scaleSize = 1;
  double scaleSizeNow = 1;

  // 计算偏移
  double offsetX = 0;
  double offsetXNow = 0;
  double offsetY = 0;
  double offsetYNow = 0;

  // 平移
  void scroll(double x, double y) {
    print("偏移: $x $y $offsetX $offsetXNow ${line1.length}");
    print("计算: ${offsetX + x} $left ${offsetX + (line1.length - 1) * scaleSize + x} ${width - right}");
    if (offsetX + x > left) {
      // 禁止左滑
      return;
    }
    if (offsetX + (line1.length - 1) * scaleSize + x < width - right) {
      // 禁止右滑
      return;
    }
    offsetXNow = offsetX + x;
    offsetYNow = offsetY + y;
    repaint.value++;
    update();
  }

  // 停止平移
  void endScroll() {
    offsetX = offsetXNow;
    offsetY = offsetYNow;
    repaint.value++;
    update();
  }

  /// 缩放
  void scale(double scale) {
    scaleSizeNow = scaleSize * scale;
    offsetXNow = scaleSize * scale;
    repaint.value++;
    update();
  }

  /// 停止缩放
  void endScale() {
    scaleSize = scaleSizeNow;
    offsetX = offsetXNow;
    repaint.value++;
    update();
  }

  Future initLine1() async {
    int i = 0;
    var random = Random();
    while (i < 1000) {
      line1.add(random.nextInt(120) + random.nextDouble());
      i++;
    }
    repaint.value++;
    update();
  }
}

class LinePainter extends CustomPainter {
  // // 重绘
  // final ValueNotifier repaint;

  LineChartController chartController;

  LinePainter(LineChartController this.chartController) : super(repaint: chartController.repaint);

  final GlobalKey<FormState> _abcKey = GlobalKey<FormState>();

  double left = 80.w;
  double top = 60.w;
  double right = 80.w;
  double bottom = 60.w;

  @override
  void paint(Canvas canvas, Size size) {
    if (chartController.width == 0.w || chartController.height == 0.w) {
      chartController.width = size.width;
      chartController.height = size.height;
    }
    // 竖线 左到有 从上往下画
    for (double i = left; i < size.width - right; i += ((size.width - left - right) / 7)) {
      canvas.drawLine(Offset(i, top), Offset(i, size.height - bottom), chartController.paintText);
    }
    // 横线 上到下 从左往右画
    for (double i = top; i < size.height - bottom; i += ((size.height - top - bottom) / 7)) {
      canvas.drawLine(Offset(left, i), Offset(size.width - right, i), chartController.paintText);
    }

    // 边框
    canvas.drawLine(Offset(left, top), Offset(left, size.height - bottom), chartController.paint);
    canvas.drawLine(Offset(left, top), Offset(size.width - right, top), chartController.paint);
    canvas.drawLine(Offset(size.width - right, top), Offset(size.width - right, size.height - bottom), chartController.paint);
    canvas.drawLine(Offset(left, size.height - bottom), Offset(size.width - right, size.height - bottom), chartController.paint);

    // 绘制文本
    // Y1单位
    TextPainter(
      text: TextSpan(
        text: chartController.y1Unit,
        style: TextStyle(color: Colors.black, fontSize: 24.w),
      ),
      textDirection: TextDirection.ltr,
    )
      ..layout(minWidth: 40.w, maxWidth: left - 10.w)
      ..paint(canvas, Offset(10.w, 10.w));
    // Y 最小最大
    TextPainter(
      text: TextSpan(
        text: chartController.maxY1.toStringAsFixed(2),
        style: TextStyle(color: Colors.black, fontSize: 20.w),
      ),
      textDirection: TextDirection.ltr,
    )
      ..layout(minWidth: 40.w, maxWidth: left - 10.w)
      ..paint(canvas, Offset(10.w, top - 20.w));
    TextPainter(
      text: TextSpan(
        text: chartController.minY1.toStringAsFixed(2),
        style: TextStyle(color: Colors.black, fontSize: 20.w),
      ),
      textDirection: TextDirection.ltr,
    )
      ..layout(minWidth: 40.w, maxWidth: left - 10.w)
      ..paint(canvas, Offset(10.w, size.height - bottom - 20.w));

    // X 单位
    TextPainter(
      text: TextSpan(
        text: chartController.xUnit,
        style: TextStyle(color: Colors.black, fontSize: 24.w),
      ),
      textDirection: TextDirection.ltr,
    )
      ..layout(minWidth: 40.w, maxWidth: 60.w)
      ..paint(canvas, Offset(size.width - 40.w, size.height - 40.w));
    // X
    TextPainter(
      text: TextSpan(
        text: (chartController.minX).toStringAsFixed(2),
        style: TextStyle(color: Colors.black, fontSize: 20.w),
      ),
      textDirection: TextDirection.ltr,
    )
      ..layout(minWidth: 40.w, maxWidth: 60.w)
      ..paint(canvas, Offset(left - 20.w, size.height - 30.w));
    TextPainter(
      text: TextSpan(
        text: (chartController.maxX).toStringAsFixed(2),
        style: TextStyle(color: Colors.black, fontSize: 20.w),
      ),
      textDirection: TextDirection.ltr,
    )
      ..layout(minWidth: 40.w, maxWidth: 60.w)
      ..paint(canvas, Offset(size.width - right - 20.w, size.height - (bottom / 2)));

    // 绘制三角形 当前值
    if (chartController.offsetXNow >= left && chartController.offsetXNow <= (size.width - right)) {
      canvas.drawLine(
          Offset(chartController.offsetXNow, top), Offset(chartController.offsetXNow, size.height - bottom), chartController.paintCurrent);
    }

    // 绘制line1 点
    List<Offset> point1 = [];
    for (int i = 0; i < chartController.line1.length; i++) {
      var x = left + i * chartController.scaleSizeNow + chartController.offsetXNow;
      var y = top + (size.height - top - bottom) / 120 * chartController.line1[i];
      print("绘制点信息 $x $y");
      point1.add(Offset(x, y));
      // 绘制点
      if (x >= left && x <= size.width - right) {
        canvas.drawCircle(Offset(x, y), 2.w, chartController.paintPoint);
      }
    }
    // 绘制线
    for (int i = 1; i < point1.length; i++) {
      if (point1[i - 1].dx >= left && point1[i - 1].dx <= size.width - right && point1[i].dx >= left && point1[i].dx <= size.width - right) {
        canvas.drawLine(point1[i - 1], point1[i], chartController.paintPoint);
      }
    }
  }

  /// 绘制
  void drawAxis() {}

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }
}

class AxisWidget extends StatefulWidget {
  LineChartController chartController;

  AxisWidget(this.chartController);

  @override
  State<StatefulWidget> createState() => AxisWidgetState();
}

class AxisWidgetState extends State<AxisWidget> {
  double downX = -1;
  double downY = -1;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {},
      onDoubleTap: () {},
      onTapDown: (TapDownDetails details) {
        print("按下 ${details.localPosition.dx} ${details.localPosition.dy}");
        downX = details.localPosition.dx;
        downY = details.localPosition.dy;
      },
      onScaleStart: (ScaleStartDetails details) {
        print("开始 ${details.localFocalPoint.dx} ${details.localFocalPoint.dy}");
        downX = details.localFocalPoint.dx;
        downY = details.localFocalPoint.dy;
      },
      onScaleUpdate: (ScaleUpdateDetails details) {
        print("移动 ${details.localFocalPoint.dx} ${details.localFocalPoint.dy}");
        print("缩放 ${details.scale}");
        widget.chartController.scroll(details.localFocalPoint.dx - downX, details.localFocalPoint.dy - downY);
        if (details.scale != 1.0) widget.chartController.scale(details.scale);
      },
      onScaleEnd: (ScaleEndDetails details) {
        print("结束: ${details.pointerCount}");
        widget.chartController.endScroll();
        widget.chartController.endScale();
      },
      child: Container(
        alignment: Alignment.center,
        child: CustomPaint(painter: LinePainter(widget.chartController), size: Size(750.w, 750.w)),
      ),
    );
  }
}
